package utils

import (
	"fmt"
	"github.com/robfig/revel"
	"github.com/russross/blackfriday"
	"labix.org/v2/mgo/bson"
	"reflect"
	"strings"
)

var (
	DbUrl, DbName, Summary string
)

const (
	NAME_EXISTS = "name exits"
)

func init() {

	DbUrl = "127.0.0.1"
	DbName = "Blog"
	/*	abc, _ := revel.Config.String("cookie.httponly")
		revel.INFO.Printf("Hello Conifg cookie.httponly ", abc)*/
	Summary = "<!--summary--!>"
	revel.INFO.Printf("DbUrl: ", DbUrl)
}

func GetSummary(markdown string) (summary string) {
	revel.INFO.Printf("包含:", strings.Contains(markdown, Summary))
	s := strings.Split(markdown, Summary)
	revel.INFO.Printf("summary: ", s[0])
	summary = string(blackfriday.MarkdownCommon([]byte(s[0])))
	return
}

// Custom TypeBinder for bson.ObjectId
// Makes additional Id parameters in actions obsolete
var ObjectIdBinder = revel.Binder{
	// Make a ObjectId from a request containing it in string format.
	Bind: revel.ValueBinder(func(val string, typ reflect.Type) reflect.Value {
		if len(val) == 0 {
			return reflect.Zero(typ)
		}
		if bson.IsObjectIdHex(val) {
			objId := bson.ObjectIdHex(val)
			return reflect.ValueOf(objId)
		} else {
			revel.ERROR.Print("ObjectIdBinder.Bind - invalid ObjectId!")
			return reflect.Zero(typ)
		}
	}),
	// Turns ObjectId back to hexString for reverse routing
	Unbind: func(output map[string]string, name string, val interface{}) {
		var hexStr string
		hexStr = fmt.Sprintf("%s", val.(bson.ObjectId).Hex())
		// not sure if this is too carefull but i wouldn't want invalid ObjectIds in my App
		if bson.IsObjectIdHex(hexStr) {
			output[name] = hexStr
		} else {
			revel.ERROR.Print("ObjectIdBinder.Unbind - invalid ObjectId!")
			output[name] = ""
		}
	},
}
